﻿namespace MF.HSD.UpdateSalePriceListIspBP
{
	using System;
	using System.Collections.Generic;
    using System.Data;
    using System.Text;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.DTOs;
    using UFIDA.U9.CA.CalculateCost;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.CBO.SCM.Customer;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.ISV.PC;
    using UFIDA.U9.ISV.SM;
    using UFIDA.U9.ISV.SM.Proxy;
    using UFIDA.U9.SPR.SalePriceAdjustment;
    using UFIDA.U9.SPR.SalePriceList;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Exceptions;
    using UFSoft.UBF.PL.Engine.Cache;
    using UFSoft.UBF.Util.Context;
    using UFSoft.UBF.Util.DataAccess;

    /// <summary>
    /// UpdateSalePrice partial 
    /// </summary>	
	public partial class UpdateSalePrice 
	{	
		internal BaseStrategy Select()
		{
			return new UpdateSalePriceImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class UpdateSalePriceImpementStrategy : BaseStrategy
	{
		public UpdateSalePriceImpementStrategy() { }

		public override object Do(object obj)
		{						
			UpdateSalePrice bpObj = (UpdateSalePrice)obj;

            string sql = $"select ci.ID IID,(1+CONVERT(DECIMAL(10, 2),cc.DescFlexField_PrivateDescSeg4))*iic.ElementTypeCost_MaterialCurrentCost CurrentCost from CBO_ItemMaster ci   inner join CBO_Category cc on ci.StockCategory = cc.ID  inner join Base_Organization o on o.ID = ci.Org  inner join IC_ItemInvCost iic on ci.ID = iic.ItemInfo_ItemID  inner join Base_SOBAccountingPeriod sop on iic.SOBPeriod = sop.ID where cc.DescFlexField_PrivateDescSeg4 != '' and sop.DisplayName like '{DateTime.Parse(DateTime.Now.ToString("yyyy-MM")).AddMonths(-1)}' and o.ID = '{Context.LoginOrg.ID}'";
            DataSet ds = null;
            List<ItemDTO> itemDTOs = new List<ItemDTO>();
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql.ToString(), null, out ds);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0) 
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    ItemDTO item1 = new ItemDTO();
                    item1.IID =  long.Parse(item["IID"].ToString());
                    item1.CurrentCost = decimal.Parse(item["CurrentCost"].ToString());
                    itemDTOs.Add(item1);
                }
            }

            string sql1 = $"SELECT c.ID CID,c.PriceListID JBID FROM CBO_Customer c inner join Base_Contact bc on c.DefaultContact = bc.ID \r\ninner join Base_Organization o on o.ID = c.Org \r\nwhere bc.IsOrgContact = 1 and o.ID = '{Context.LoginOrg.ID}'";
            ds = null;
            List<CustDTO> CustWJBDTOs = new List<CustDTO>();
            List<CustDTO> CustJBDTOs = new List<CustDTO>();
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql1.ToString(), null, out ds);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    if (!string.IsNullOrEmpty(item["JBID"].ToString()) && item["JBID"].ToString() != "-1")
                    {
                        CustDTO item1 = new CustDTO();
                        item1.CID = long.Parse(item["CID"].ToString());
                        item1.Items = new List<ItemDTO>();
                        item1.JBID = long.Parse(item["JBID"].ToString());
                        CustJBDTOs.Add(item1);
                    }
                    else 
                    {
                        CustDTO item1 = new CustDTO();
                        item1.CID = long.Parse(item["CID"].ToString());
                        item1.Items = new List<ItemDTO>();
                        item1.JBID = 0;
                        CustWJBDTOs.Add(item1);
                    }
                }
            }

            //有价表最终集合赋值
            foreach (var item in CustJBDTOs)
            {
                item.Items = itemDTOs;
            }            
            //无价表最终集合赋值
            foreach (var item in CustWJBDTOs) 
            {
                item.Items = itemDTOs;
            }

            if (CustWJBDTOs.Count > 0) 
            {
                foreach (var item in CustWJBDTOs)
                {
                    CreateXSJB(item);
                }
            }

            string jbid = "";
            if(CustJBDTOs.Count>0)
            {
                foreach (var item in CustJBDTOs)
                {
                    //foreach (var itemDTO in item.Items) 
                    //{
                    //    jbid += "," + itemDTO.IID;
                    //}
                    //string deletejb = $"delete from SPR_SalePriceLine where ID in ({jbid.Substring(1)});delete from SPR_SalePriceLine_trl where ID in({jbid.Substring(1)})";
                    //DataAccessor.RunSQL(DataAccessor.GetConn(), deletejb.ToString(), null);
                    CreateSalePriceAdjustDoc(item);
                }
            }
            return 0;
		}


        public void CreateXSJB(CustDTO cust) 
        {
            CommonCreateSalePriceListSRVProxy client = new CommonCreateSalePriceListSRVProxy();
            client.SalePricelistDtos = new List<SalePriceListDTOData>();

            List<SalePriceListDTOData> docList = new List<SalePriceListDTOData>();//头集合
            SalePriceListDTOData doc = new SalePriceListDTOData();//头
            List<SalePriceLineDTOData> lines = new List<SalePriceLineDTOData>();//行集合
            
            Customer customer = Customer.Finder.FindByID(cust.CID);
            #region  头赋值                
            //价表编码
            doc.Code = customer.Code;
            //价表名称
            doc.Name = customer.Name;
            //组织
            doc.Org = new CommonArchiveDataDTOData();
            doc.Org.ID = customer.Org.ID;
            doc.Org.Code = customer.Org.Code;
            doc.Org.Name = customer.Org.Name;
            //取客户档案交易币种
            CommonArchiveDataDTOData idc = new CommonArchiveDataDTOData();
            idc.ID = customer.TradeCurrency.ID;
            idc.Code = customer.TradeCurrency.Code;
            idc.Name = customer.TradeCurrency.Name;
            doc.Currency = idc;

            doc.IsIncludeTax = true;
            doc.Discription = "";
            #endregion

            int doclinenum = 10;
            #region  行赋值   
            foreach (var i in cust.Items)
            {
                if (i.CurrentCost!=0)
                {
                    SalePriceLineDTOData line = new SalePriceLineDTOData();//行
                    line.DocLineNo = doclinenum;
                    ItemMaster itemMaster = ItemMaster.Finder.FindByID(i.IID);
                    //料品
                    ItemInfoData item = new ItemInfoData();
                    item.ItemID = itemMaster.ID;
                    item.ItemCode = itemMaster.Code;
                    item.ItemName = itemMaster.Name;
                    line.ItemInfo = item;

                    //价格
                    line.Price = i.CurrentCost;

                    //计价单位
                    CommonArchiveDataDTOData uom = new CommonArchiveDataDTOData();
                    uom.ID = itemMaster.PriceUOM.ID;
                    uom.Code = itemMaster.PriceUOM.Code;
                    uom.Name = itemMaster.PriceUOM.Name;
                    line.Uom = uom;
                    //添加价表行
                    lines.Add(line);
                    doclinenum += 10;
                }
            }
            #endregion
            doc.SalePriceLines = lines;
            docList.Add(doc);
            client.SalePricelistDtos = docList;
            List <CommonArchiveDataDTOData> result = client.Do();
            //绑定价表
            if (result.Count > 0 && result[0].ID != 0)
            {
                using (ISession session = Session.Open())
                {
                    customer.PriceListID = result[0].ID;
                    session.Modify(customer);
                    session.Commit();
                }
            }
        }

        public void CreateSalePriceAdjustDoc(CustDTO cust)
        {
            //调价单头集合
            List<UFIDA.U9.ISV.SM.SalePriceAdjustmentDTOData> lists = new List<UFIDA.U9.ISV.SM.SalePriceAdjustmentDTOData>();
            //调价单行集合
            List<UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData> lines = new List<UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData>();
            //调价单行
            UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData line = new UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData();

            //调价单头
            UFIDA.U9.ISV.SM.SalePriceAdjustmentDTOData list = new UFIDA.U9.ISV.SM.SalePriceAdjustmentDTOData();
            #region  调价单头
            //名称
            //list.Name = "PL" + DateTime.Now.ToString("yy-MM-dd") + "001";
            //是否依赖
            list.IsDepended = false;
            //状态
            list.Status = 0;
            //描述
            list.Discription = "价格调整";
            list.DocumentType = new UFIDA.U9.Base.DTOs.IDCodeNameDTOData();

            //价表
            SalePriceList salePriceList = SalePriceList.Finder.FindByID(cust.JBID);
            UFIDA.U9.Base.DTOs.IDCodeNameDTOData pl = new UFIDA.U9.Base.DTOs.IDCodeNameDTOData();
            pl.ID = salePriceList.ID;
            pl.Code = salePriceList.Code;
            pl.Name = salePriceList.Name;
            list.PriceList = pl;

            //单据类型
            UFIDA.U9.Base.DTOs.IDCodeNameDTOData dt = new UFIDA.U9.Base.DTOs.IDCodeNameDTOData();
            SalePriceAdjustmentDocType doctype = SalePriceAdjustmentDocType.Finder.Find($"Code='SDTJ0001' and Org.ID = {Context.LoginOrg.ID}");
            dt.ID = doctype.ID;
            dt.Code = doctype.Code;
            dt.Name = doctype.Name;
            list.DocumentType = dt;
            #endregion

            list.SalePriceAdjustLines = new List<UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData>();
            int doclinenum = 10;
            foreach (var soLineDTO in cust.Items)
            {
                line = new UFIDA.U9.ISV.SM.SalePriceAdjustLineDTOData();
                ItemMaster itemMaster = ItemMaster.Finder.FindByID(soLineDTO.IID);
                #region  调价单行
                line.DocLineNo = doclinenum;
                line.NewPrice = soLineDTO.CurrentCost;
                //line.PriceWave = salePriceList.Price;
                line.SrcDocNo = "";
                //料品
                UFIDA.U9.CBO.SCM.Item.ItemInfoData item = new UFIDA.U9.CBO.SCM.Item.ItemInfoData();
                item.ItemID = itemMaster.ID;
                item.ItemCode = itemMaster.Code;
                item.ItemName = itemMaster.Name;
                line.ItemInfo = item;

                //计价单位
                UFIDA.U9.Base.DTOs.IDCodeNameDTOData uom = new UFIDA.U9.Base.DTOs.IDCodeNameDTOData();
                uom.ID = itemMaster.PriceUOM.ID;
                uom.Code = itemMaster.PriceUOM.Code;
                uom.Name = itemMaster.PriceUOM.Name;
                line.Uom = uom;

                //行有效期
                line.FromDate = DateTime.Now;
                line.ToDate = DateTime.Parse("9999.12.31");
                #endregion

                //添加价表行
                list.SalePriceAdjustLines.Add(line);
                doclinenum += 10;
            }
            lists.Add(list);
            // 服务调用

            UFIDA.U9.ISV.SM.Proxy.CreateSalePriceAdjustmentSRVProxy proxy = new UFIDA.U9.ISV.SM.Proxy.CreateSalePriceAdjustmentSRVProxy();
            proxy.SalePriceAdjustmentDTO = lists;
            List<UFIDA.U9.Base.DTOs.IDCodeNameDTOData> resultList = proxy.Do();
            if (resultList.Count>0 && resultList[0].ID!=0) 
            {
                SubmitSalePriceAdjustmentSRV salePriceAdjustmentSRV = new SubmitSalePriceAdjustmentSRV();
                salePriceAdjustmentSRV.SalePriceAdjustmentDTOs = new List<UFIDA.U9.Base.DTOs.IDCodeNameDTO>();
                IDCodeNameDTO iddto = new IDCodeNameDTO();
                iddto.ID = resultList[0].ID;
                salePriceAdjustmentSRV.SalePriceAdjustmentDTOs.Add(iddto);
                salePriceAdjustmentSRV.Do();
                PLCacheManager.DataCache.FlushCache();
                PLCacheManager.ObjectCache.FlushCache();
                ApprovedSalePriceAdjustmentSRV approvedSalePrice = new ApprovedSalePriceAdjustmentSRV();
                approvedSalePrice.SalePriceAdjustmentDTOs = new List<IDCodeNameDTO> { iddto };
                approvedSalePrice.Do();
            }
        }

        public class CustDTO 
        {
            public long CID { get; set; }
            public long JBID { get; set; }
            public List<ItemDTO> Items { get; set; }
        }

        public class ItemDTO
        {
            public long IID { get; set; }
            public long JBID { get; set; }
            public decimal CurrentCost { get; set; }
        }

        public class RedDTO
        {
            public long IID { get; set; }
            public long CID { get; set; }
            public long JBID { get; set; }
            public decimal CurrentCost { get; set; }
        }
    }
	#endregion
}